package com.gskj.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.gskj.eduorder.entity.Order;
import com.gskj.eduorder.entity.PayLog;
import com.gskj.eduorder.mapper.PayLogMapper;
import com.gskj.eduorder.service.IOrderService;
import com.gskj.eduorder.service.IPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gskj.servicebase.exceptionhandler.GuLiException;
import com.gskj.utils.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author Connor
 * @since 2020-08-17
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements IPayLogService {

    @Autowired
    private IOrderService orderService;


    @Override
    public Map<String, Object> createQRCodeUrl(String orderNo) {

        // 1. 根据订单号 查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderService.getOne(wrapper);

        // 2. 通过map 设置 生成微信的参数
        Map<String, String> setting = new HashMap<>();
        // 2.1 设置支付参数
        setting.put("appid", "wx74862e0dfcf69954"); //关联的公众号
        setting.put("mch_id", "1558950191"); // 商户号
        setting.put("nonce_str", WXPayUtil.generateNonceStr());
        setting.put("body", order.getCourseTitle()); // 课程标题
        setting.put("out_trade_no", orderNo);  // 订单号
        setting.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + ""); // 金额
        setting.put("spbill_create_ip", "127.0.0.1"); // 支付 IP(本地)
        setting.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify"); // 回调uel
        setting.put("trade_type", "NATIVE"); // 生成二维码类型

        // 3. 发送HttpClient 请求，传递参数为 xml 格式，微信支付的提供的固定地址
        // url 为商户key，
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

        try {
            // 3.1 设置xml格式参数
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(setting, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            // 设置 支持 https
            httpClient.setHttps(true);
            // 发送请求
            httpClient.post();

            // 得到返回的内容，(内容为 xml格式)
            String contentXml = httpClient.getContent();

            // 将xml 格式 转换为 map集合。并返回
            Map<String, String> contentMap = WXPayUtil.xmlToMap(contentXml);

            // 最终返回数据的封装
            Map<String, Object> result = new HashMap<>();

            result.put("out_trade_no", orderNo);
            result.put("course_id", order.getCourseId());
            result.put("total_fee", order.getTotalFee());
            result.put("result_code", contentMap.get("result_code")); // 微信响应 状态码
            result.put("code_url", contentMap.get("code_url")); // 微信二维码 地址

            // 返回
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuLiException(20001, "生成二维码失败！");
        }
    }

    @Override
    public Map<String, String> checkPayState(String orderNo) {
        try {
            // 1. 封装微信查询参数
            Map<String, String> params = new HashMap<>();
            params.put("appid", "wx74862e0dfcf69954");
            params.put("mch_id", "1558950191");
            params.put("out_trade_no", orderNo);
            params.put("nonce_str", WXPayUtil.generateNonceStr());

            // 2. 设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(params, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            // 3. 返回第三方数据
            String contentXml = client.getContent();

            // 4. 转为 map,返回
            Map<String, String> contentMap = WXPayUtil.xmlToMap(contentXml);
            return contentMap;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void updateOrderStatus(Map<String, String> stateMap) {

        // 从map中获取 订单号
        String orderNo = stateMap.get("out_trade_no");

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderService.getOne(wrapper);

        // 判断当前订单支付状态 为1 ，直接return
        if (order.getStatus().intValue() == 1) {
            return;
        }
        // 设置 status 为1 (已支付)
        order.setStatus(1);
        // 修改 order
        orderService.updateById(order);

        // 记录支付日志
        PayLog payLog = new PayLog();
        payLog.setOrderNo(order.getOrderNo());//支付订单号
        payLog.setPayTime(new Date());
        payLog.setPayType(1);//支付类型(微信)
        payLog.setTotalFee(order.getTotalFee());//总金额(分)
        payLog.setTradeState(stateMap.get("trade_state"));//支付状态
        payLog.setTransactionId(stateMap.get("transaction_id")); // 订单流水号

        // 将订单的其他属性(json格式 )放入到 日志表中
        payLog.setAttr(JSONObject.toJSONString(stateMap));

        baseMapper.insert(payLog);//插入到支付日志表
    }
}
